import React, { useCallback, useEffect, useState } from "react";

interface Props<T> {
  api: (params?: any) => Promise<T[]>;
  offset: boolean;
}

export function DataList<T>({ api, offset = true, ...restProps }: Props<T>) {
  const [loaded, setLoaded] = useState(false);

  const [append, setAppend] = useState(false);

  const [refresh, setRefresh] = useState(false);

  const [loading, setLoading] = useState(false);

  const [data, setData] = useState<T[]>([]);

  const loadData = useCallback(
    async (refresh = false) => {
      let key: any;
      if (offset) key = refresh ? 0 : data?.length;
      else {
        key = refresh && data?.length ? 0 : (data[data.length - 1] as any)?.id;
      }
      try {
        setLoading(true);
        const res = await api(key);
        // if ((res.length === 10)) setAppend(true);
        // else setAppend(false);
        setAppend(res?.length === 10);
        setData((prvData) => (refresh ? res : prvData.concat(res)));
      } catch (error) {}
      //
      setLoading(false);
    },
    [api]
  );

  //    api 发生变化的时候加载数据
  useEffect(() => {
    loadData(true);
  }, [api]);

  return (
    <div className="outer">
      <div className="header">
        {/*  内容 */}
        <div>{loading && <span>loading</span>}</div>
      </div>
      <div className="footer">
        {!!data.length && !loading && (
          <span>{append ? "上拉加载更多" : "到底了"}</span>
        )}
      </div>
    </div>
  );
}
